package pl.edu.pw.elka.tinyrepo.common;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import com.thoughtworks.xstream.XStream;

/**
 * Serializacja i deserializacja obiektow typu FileProperties do i z formatu XML
 * Uzywany przez DataServer i (prawdopodobnie) przez klienta.
 * Wrapper na XStream
 * 
 * @author Dominik Oledzki
 *
 */
public class FilePropertiesSerializer {
	private XStream xstream;

	public FilePropertiesSerializer() {
		xstream = new XStream();
		xstream.alias("FileProperties", FileProperties.class);
	}
	
	/**
	 * Serializuje wlasciwosci pliku (FileProperties) do XMLa
	 * 
	 * @param properties - obiekt do serializacji
	 * @return zserializowany obiekt w postaci XMLa
	 */
	public String toXML(FileProperties properties) {
		String xml = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			Writer writer = new OutputStreamWriter(out, "UTF-8");
			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
			xstream.toXML(properties, writer);
			xml = out.toString("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml;
	}
	
	/**
	 * Deserializuje wlasciwosci pliku z formatu XML do obiektu klasy FileProperties
	 * @param xml - zserializowany obiekt FileProperties
	 * @return zdeserializowany obiekt FileProperties
	 */
	public FileProperties fromXML(String xml) {
		return (FileProperties)xstream.fromXML(xml);
	}
}
